<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>test</title>
  </head>
  <body>
    <button id="app" onclick="test()">测距 直接点击会使用默认值 key需要输入</button>
    <br/>
    <input id="origins" class="content" placeholder="起点经纬坐标"/>
    <br/>
    <input id="destination" class="content" placeholder="目标点经纬坐标"/>
    <br/>
    <input id="key" class="content" placeholder="注册获取key"/>
    <br/>
    <input id="type" class="content" placeholder="测距方式 默认0直线距离 1驾车导航距离 3步行规划距离"/>
    <br/>
    <input id="result" class="content" placeholder="结果" disabled/>
    <br/>
    <input id="all" class="content" placeholder="错误" disabled/>
  </body>
  <script type="text/javascript">
      function test() {
          document.getElementById("origins").value = "116.481028,39.989643";
          let origins = document.getElementById("origins").value;
          document.getElementById("destination").value = "114.465302,40.004717";
          let destination = document.getElementById("destination").value;
          document.getElementById("result").value = getDistance(origins, destination) + "千米";
      }

      //官方api可传多个origins 未做实现
      function getDistance(origins, destination) {
          let key = document.getElementById("key").value;
          let type = document.getElementById("type").value;
          if (type == null || type === '') type = 0;
          let url = `https://restapi.amap.com/v3/distance?origins=${origins}&destination=${destination}&output=json&key=${key}&type=${type}`
          let xhr = new XMLHttpRequest();
          xhr.open("get", url, false);
          let distance = Number(0);
          xhr.onreadystatechange = function () {
              if (xhr.readyState === 4 && xhr.status === 200) {
                  let result = JSON.parse(xhr.response);
                  if (result.status === "1") {
                      distance = result.results[0].distance / 1000;
                  }
                  document.getElementById("all").value = xhr.response;
              }
          }
          xhr.send();
          return distance;
      }
  </script>
  <style>
      .content {
          width: 700px;
      }
  </style>
</html>
